﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;

using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.Mtbl;

namespace WebApplication
{
    public partial class MainMarket : BasePage
    {
        private static tblCustomer entCust = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string uid = Request.QueryString[Constant.UrlParamName.CustomerUID];
                if (string.IsNullOrEmpty(uid))
                {
                    usermeg.Visible = false;
                    LbtnSave.Enabled = false;
                }
                else
                {
                    usermeg.Visible = true;
                    entCust = new tblCustomer();
                    tblCustomerBLL bll = tblCustomerBLL.GetInstance();
                    entCust.CustomerUID = int.Parse(uid);
                    entCust = bll.GetEntity(entCust);
                }
                Band_All();
            }
        }


        #region 7个大洲 的国家绑定 为了降低程序的可读性和维护性，一个个绑定(损失了程序的复用性)，也是为了客户以后提出新的想法，往细里改做铺垫

        /// <summary>
        /// 绑定所有大洲的所有国家
        /// </summary>
        private void Band_All()
        {
            Band_1(); Band_2(); Band_3(); Band_4(); Band_5(); Band_6(); Band_7();

            //把值绑定到 checkboxlist里
            if (entCust != null)
                GetValueBindlist(entCust.CustomerUID);            
        }

        /// <summary>
        /// 绑定亚洲的国家
        /// </summary>
        private void Band_1()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 1;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList2.DataSource = tmp_list;
            CheckBoxList2.DataTextField = "LastModifyBy";
            CheckBoxList2.DataValueField = "CountryUID";
            CheckBoxList2.DataBind();            
        }

        /// <summary>
        /// 绑定中东的国家
        /// </summary>
        private void Band_2()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 2;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList5.DataSource = tmp_list;
            CheckBoxList5.DataTextField = "LastModifyBy";
            CheckBoxList5.DataValueField = "CountryUID";
            CheckBoxList5.DataBind();
        }

        /// <summary>
        /// 绑定澳洲的国家
        /// </summary>
        private void Band_3()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 3;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList3.DataSource = tmp_list;
            CheckBoxList3.DataTextField = "LastModifyBy";
            CheckBoxList3.DataValueField = "CountryUID";
            CheckBoxList3.DataBind();
        }

        /// <summary>
        /// 绑定非洲的国家
        /// </summary>
        private void Band_4()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 4;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList1.DataSource = tmp_list;
            CheckBoxList1.DataTextField = "LastModifyBy";
            CheckBoxList1.DataValueField = "CountryUID";
            CheckBoxList1.DataBind();
        }

        /// <summary>
        /// 绑定北美洲的国家
        /// </summary>
        private void Band_5()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 5;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList6.DataSource = tmp_list;
            CheckBoxList6.DataTextField = "LastModifyBy";
            CheckBoxList6.DataValueField = "CountryUID";
            CheckBoxList6.DataBind();
        }

        /// <summary>
        /// 绑定南美洲的国家
        /// </summary>
        private void Band_6()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 6;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList7.DataSource = tmp_list;
            CheckBoxList7.DataTextField = "LastModifyBy";
            CheckBoxList7.DataValueField = "CountryUID";
            CheckBoxList7.DataBind();
        }

        /// <summary>
        /// 绑定欧洲的国家
        /// </summary>
        private void Band_7()
        {
            mtblCountry ent = new mtblCountry();
            ent.AreaUID = 7;
            List<mtblCountry> tmp_list = new List<mtblCountry>();
            tmp_list = mtblCountryBLL.GetInstance().GetListByENT(ent);

            for (int i = 0; i < tmp_list.Count(); i++)
                tmp_list[i].LastModifyBy = tmp_list[i].Country_Eng + " " + tmp_list[i].Country_Chi;

            CheckBoxList4.DataSource = tmp_list;
            CheckBoxList4.DataTextField = "LastModifyBy";
            CheckBoxList4.DataValueField = "CountryUID";
            CheckBoxList4.DataBind();
        }

        /// <summary>
        /// 取到国家的id值绑定到 CheckBoxList里
        /// </summary>
        /// <param name="list"></param>
        /// <param name="cbl"></param>
        private void GetValueBindlist(int CustomerUID)
        {
            List<tblCust_Market> list = new List<tblCust_Market>();
            tblCust_MarketBLL bll = tblCust_MarketBLL.GetInstance();
            tblCust_Market tmp = new tblCust_Market();
            tmp.CustomerUID = CustomerUID;
            tmp.Deleted = Constant.IsDelete.no;
            list = bll.GetListByENT(tmp);

            CheckBoxList[] cbls = { CheckBoxList1, CheckBoxList2, CheckBoxList3, CheckBoxList4, CheckBoxList5, CheckBoxList6, CheckBoxList7 };

            foreach (CheckBoxList cbl in cbls)
            {
                if (cbl != null)
                {
                    for (int i = 0; i < list.Count(); i++)
                    {
                        for (int j = 0; j < cbl.Items.Count; j++)
                        {
                            if (cbl.Items[j].Value == list[i].CountryUID.ToString())
                            {
                                cbl.Items[j].Selected = true;
                                HiddenField_val.Value += cbl.Items[j].Value + ",";
                            }
                        }
                    }
                }
            }
        }

        #endregion

        private void _save(List<int> listCountryUID,int custUID)
        {
            tblCust_MarketBLL bll = new tblCust_MarketBLL();
            for (int i = 0; i < listCountryUID.Count(); i++)
            {
                tblCust_Market tmp = new tblCust_Market();
                tmp.CustomerUID = custUID; tmp.CountryUID = listCountryUID[i];
                List<tblCust_Market> list_tmp = bll.GetListByENT(tmp);
                if (list_tmp.Count()<= 0)
                {
                    tmp.Deleted = Constant.IsDelete.no;
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.InsertENT(tmp);
                }
                else
                {
                    tmp = list_tmp[0];
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.UpdateENT(tmp);
                }                
            }
        }

        private void _delete(List<int> listCountryUID, int custUID)
        {
            tblCust_MarketBLL bll = new tblCust_MarketBLL();
            for (int i = 0; i < listCountryUID.Count(); i++)
            {
                tblCust_Market tmp = new tblCust_Market();
                tmp.CustomerUID = custUID; tmp.CountryUID = listCountryUID[i];
                List<tblCust_Market> list_tmp = bll.GetListByENT(tmp);
                if (list_tmp.Count() > 0)
                {
                    tmp = list_tmp[0];
                    tmp.Deleted = Constant.IsDelete.yes;
                    tmp.LastModifyBy = Session[Constant.SessionName.Manage] == null ? "system" : (Session[Constant.SessionName.Manage] as tblUser).User_Name.Trim();
                    bll.UpdateENT(tmp);
                }
            }
        }

        protected void LbtnSave_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            if (entCust != null)
            {
                int custUID = entCust.CustomerUID;
                //被选中的
                List<int> selected_uid = new List<int>();
                //未被选中的
                List<int> unselected_uid = new List<int>();

                CheckBoxList[] cbls = { CheckBoxList1, CheckBoxList2, CheckBoxList3, CheckBoxList4, CheckBoxList5, CheckBoxList6, CheckBoxList7 };
                foreach (CheckBoxList cbl in cbls)
                {
                    if (cbl != null)
                    {
                        for (int i = 0; i < cbl.Items.Count; i++)
                        {
                            if (cbl.Items[i].Selected)
                                selected_uid.Add(int.Parse(cbl.Items[i].Value));
                            else
                                unselected_uid.Add(int.Parse(cbl.Items[i].Value));
                        }
                    }
                }
                _save(selected_uid, custUID);//选中项处理
                _delete(unselected_uid, custUID);//未选中项处理
                WriteToLog();
                msg = ResourceManage.GetResourceString("msg100002");
            }
            else
            {
                msg = ResourceManage.GetResourceString("msg100006");                
            }
            lblMessages.Text = msg;
        }

        protected void LbtnQuit_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/CustomerList.aspx");
        }

        protected void WriteToLog()
        {
            int uid = Convert.ToInt32(Request.QueryString[Constant.UrlParamName.CustomerUID]);
            tblUser ent = GetManageFromSession();
            string addlog = string.Empty;
            string dellog = string.Empty;
            mtblCountry entCountry = new mtblCountry();
            List<mtblCountry> list = mtblCountryBLL.GetInstance().GetListByENT(entCountry);
            string[] add = HiddenFiled_add.Value.Split(',');
            string[] delete = HiddenFiled_del.Value.Split(',');
            if (add.Length > 1 | delete.Length > 1)
            {
                for (int i = 0; i < add.Length - 1; i++)
                {
                    var result = list.Where(a => a.CountryUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                    foreach (mtblCountry item in result)
                    {
                        addlog += item.Country_Eng + ",";
                    }
                }
                for (int i = 0; i < delete.Length - 1; i++)
                {
                    var result = list.Where(a => a.CountryUID == Convert.ToInt32(delete[i])).Select(p => p).ToList();
                    foreach (mtblCountry item in result)
                    {
                        dellog += item.Country_Eng + ",";
                    }
                }
                if (addlog.Length > 1)
                    addlog = " Add " + addlog.Substring(0, addlog.Length - 1);
                else
                    addlog = "";
                if (dellog.Length > 1)
                    dellog = " Delete " + dellog.Substring(0, dellog.Length - 1);
                else
                    dellog = "";

                tblHistory entlog = new tblHistory();
                Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
                entlog.HistoryCatUID = 2;
                entlog.HistoryTypeUID = 24;
                entlog.CustomerUID = uid;
                entlog.Cust_MemberUID = 0;
                entlog.ContactPersonUID = 0;
                entlog.History_Detail = ent.User_Name + " {" + CompanyName.Text + "}{MainMarket}" + addlog + dellog;
                entlog.LastModifyBy = ent.User_Name;
                int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
            }
        }
    }
}